import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/Xwidgets/bottom_sheet.dart';
import 'package:yp/config/index.dart';
import 'package:yp/router.dart';
import 'package:yp/Xwidgets/ad_box.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/index.dart';
import 'package:yp/widgets/tab_indicator.dart';
import 'package:get/get.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'collage_logic.dart';
import 'collage_state.dart';
import 'dart:convert';

class CollagePage extends StatefulWidget {
  @override
  _CollagePageState createState() => _CollagePageState();
}

class _CollagePageState extends State<CollagePage>
    with SingleTickerProviderStateMixin {
  final CollageLogic logic = Get.put(CollageLogic());
  final CollageState state = Get.find<CollageLogic>().state;
  bool isShow=false;
  @override
  void initState() {
    super.initState();
    //
    // if (SpUtil.getInt('empeNumId') == 0 || SpUtil.getInt('empeNumId') == null) {
    //   Get.offAllNamed(RouteConfig.mallLogin, arguments: {'pintuan': '1'});
    //   return;
    // } else {
    // getTabList();
    // }
    state.collageShopId= SpUtil.getInt('storeShopNum');
    if(Get.arguments!=null&& Get.arguments['model']!=null) {
      if (Get.arguments['model']['shop_id'] != null) {
        state.collageShopId = Get.arguments['model']['shop_id'];
      }
      state.activityNumId = Get.arguments['model']['activity_num_id'];
    }
    var params = {"data_sign": 0, "system": "groupbuying",};// "ec_shop_num_id":state.collageShopId,};
    print('yiako.masterdata.general.configuration.info.search 入参:$params');
    Api.membershipInterests(params).listen((event) {
      print('yiako.masterdata.general.configuration.info.search 返回:$event');
      if (event['code'] == 0) {
        ///控制是否开启拼团活动
        var firstSwitch =
            event['info_list'][0]['ec_value'] == '1' ? true : false;
        if (event['info_list'][1] != null && firstSwitch) {
          var obj = jsonDecode(event['info_list'][1]['ec_value']);
          state.isClassify = obj['isClassify'] == '1' ? 1 : 0;
          // getTabList();
        } else {
          state.isClassify = 0;
          state.groupClassifyId=null;
          // dataInit();
        }
        getTabList();
        event['info_list'].forEach((element) {
          if (element['ec_value'].length > 1) {
            state.imageList = [];
            List imgArr =
                jsonDecode(element['ec_value'])['turnimages'].split(",");
            state.sharInfo = jsonDecode(element['ec_value']);
            imgArr.forEach((elements) {
              state.imageList.add({'logo': elements});
            });
          }
        });
      }
    });
  }

  getTabList() {

    var params = {
      "data_sign": 0,
      "channel_num_id": 98,
      "use_platform": 3,
      "ec_shop_num_id": state.collageShopId
    };

    print('ykcloud.basicdata.spellgroup.category.get 入参：$params');
    Api.categoryget(params).listen((event) {
      print('ykcloud.basicdata.spellgroup.category.get 返回：$event');
      if (event['code'] == 0) {
        state.tabList = [];
      //  setState(() {
          state.tabData = event['cat_details'];
          event['cat_details'].forEach((element) {
            state.tabList.add(Tab(text: element['cat_name'].toString()));
          });
          state.cat_id = state.tabData[0]['cat_ids'][0]['cat_id'];
          state.groupClassifyId =
              state.isClassify == 1 ? state.tabData[0]['cat1_id'] : null;
          state.controller = TabController(
              initialIndex: 0, length: state.tabList.length, vsync: this);
          isShow=true;
          print('isShow');
          print(isShow);
          dataInit();
          state.controller.addListener(() {
            state.cat_id =
                state.tabData[state.controller.index]['cat_ids'][0]['cat_id'];
            state.groupClassifyId =
                state.tabData[state.controller.index]['cat1_id'];

            dataInit();



          });
logic.update();
       // });
      }
    });
  }

  dataInit() {
    //获取今日必拼数据
    logic.getqueryspellgroup();
    //获取热拼榜数据
    logic.gethotproduct();
  }

  @override
  void dispose() {
    state.controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: YPNavigationBar(
          '超值拼团',
          showLine: false,
          backgroundColor: EsColors.Primary,
          backBtnColor: EsColors.White,
          titleColor: EsColors.White,
          showBack: kIsWeb ? false : true,
          onPressed: () {
            if (kIsWeb == true) {
              Get.offAllNamed(RouteConfig.main);
            } else {
              Get.back();
            }
          },
          actions: <Widget>[
            kIsWeb != true
                ? IconButton(
                    icon: Icon(Icons.share),
                    color: Colors.white70,
                    onPressed: () {
                      YpBottomSheet.showShareGift(context,
                          (selectIndex, selectString, {info, list}) {
                        var model;
                        var shareUrl;
                        print('22222222222');
                        print(state.sharInfo);
                        // shareUrl =   Config.WEB_URL + 'collage',
                        shareUrl = Config.H5_URL + '&isGoPintuan=true'+'&currentShopId='+ state.collageShopId.toString()+'&gbuyapplyid='+state.activityNumId.toString();
                        model = fluwx.WeChatShareWebPageModel(
                                shareUrl,
                          title:state.sharInfo['thumBnaiTitle'],
                          description: state.sharInfo['imageDesc'],
                          thumbnail: fluwx.WeChatImage.network(
                              state.imageList[0]['logo']),
                                scene: selectIndex == 0
                                    ? fluwx.WeChatScene.SESSION
                                    : fluwx.WeChatScene.TIMELINE,
                              );
                        fluwx.shareToWeChat(model);
                      }, title: '超值拼团');
                    })
                : Container(),
          ],
        ),
        body: GetBuilder<CollageLogic>(builder: (logic) {
          return Column(
            children: [
              state.isClassify == 1 ? _tabHeadder() : Container(),
              state.tabList.length > 0&&isShow ? _collageList() : Container(),
            ],
          );
        }));
  }

  ///  tab栏切换的头部
  Widget _tabHeadder() {
    return Container(
      width: double.infinity,
      color: EsColors.Primary,
      child: ExtendedTabBar(
          tabs: List<Widget>.generate(
              state.controller.length, (int index) => state.tabList[index]),
          controller: state.controller,
          // labelColor: EsColors.White,
          // labelStyle: TextStyle(color: EsColors.White, fontSize: EsSizes.LG, fontWeight: EsFontWeights.Medium),
          unselectedLabelStyle:
              TextStyle(fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal),
          isScrollable: state.controller.length > 5,
          // unselectedLabelColor: EsColors.White,

          // 自定义原型指示器
          indicator: CustomUnderlineTabIndicator(
              borderSide: BorderSide(width: 3.0, color: Colors.white),
              insets: EdgeInsets.only(bottom: 3, left: 5, right: 5))),
    );
  }

  /// 下边对应的界面
  Widget _collageList() {

    return   Expanded(
      child: TabBarView(
          physics: NeverScrollableScrollPhysics(),
          controller: state.controller,
          children: List<Widget>.generate(state.controller.length,
              (int index) => CollageIndexList(index)).toList()),
    );
  }
}

class CollageIndexList extends StatefulWidget {
  final int index;

  const CollageIndexList(this.index, {Key key}) : super(key: key);

  @override
  _CollageIndexListState createState() => _CollageIndexListState();
}

class _CollageIndexListState extends State<CollageIndexList> {
  final CollageLogic logic = Get.put(CollageLogic());
  final CollageState state = Get.find<CollageLogic>().state;

  @override
  Widget build(BuildContext context) {
    print(widget.index);
    return CustomScrollView(slivers: [
      // 广告位
      SliverToBoxAdapter(
          child: AdBox(
              aspectRatio: 355 / 145,
              adKey: 'Adv',
              height: 145,
              borderRadius: 0,
              margin: EdgeInsets.zero,
              imageList: state.imageList)), // 今日必拼
      SliverToBoxAdapter(
          child: Column(
        children: [
          _mustCollage(),
          state.hotData != null && state.hotData.length > 0
              ? _hotCollage()
              : SizedBox(),
          _tips()
        ],
      )),
      SliverList(
        delegate: SliverChildBuilderDelegate((ctx, index) {
          return _item(index);
        }, childCount: state.todayData.length),
      ),
      SliverToBoxAdapter(
          child: SizedBox(height: MediaQuery.of(context).padding.bottom + 10))
    ]);
  }

  /// 今日必拼
  Widget _mustCollage() {
    return Container(
      color: EsColors.BackGroundSecondary,
      child: Column(children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(14, 10, 14, 4),
          child: Row(
            children: [
              Image.asset('assets/images/collage_lightning.png'),
              SizedBox(width: 4),
              Text('今日必拼',
                  style: TextStyle(
                      fontSize: EsSizes.MD,
                      color: EsColors.Title,
                      fontWeight: EsFontWeights.Medium)),
              SizedBox(width: 10),
              // time(),
              Expanded(child: SizedBox()),
              // RichText(
              //     text: TextSpan(children: [
              //   TextSpan(
              //       text: '3',
              //       style: TextStyle(
              //           fontSize: EsSizes.SM,
              //           color: EsColors.Title,
              //           fontWeight: EsFontWeights.Medium)),
              //   TextSpan(
              //       text: '/4',
              //       style: TextStyle(
              //           fontSize: EsSizes.XS,
              //           color: EsColors.ContentSecondary,
              //           fontWeight: EsFontWeights.Normal))
              // ])),
            ],
          ),
        ),
        Container(
            decoration: EsDecoration.BoxShadowWithRadius,
            height: MediaQuery.of(context).size.width / 3 + 40,
            margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
            width: double.infinity,
            child: ListView.builder(
                shrinkWrap: true,
                scrollDirection: Axis.horizontal,
                itemCount: state.todayData.length,
                itemBuilder: (context, index) {
                  return Container(
                    padding: EdgeInsets.all(6),
                    child: GestureDetector(
                      onTap: () {

                        gopintuan(state.todayData[index]['g_buy_id'],state.collageShopId);
                        // Get.toNamed(RouteConfig.GroupDetailPage);
                      },
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          CachedImage(
                              width: MediaQuery.of(context).size.width / 3 - 20,
                              height:
                                  MediaQuery.of(context).size.width / 3 - 20,
                              path: state.todayData[index]['image_default_id']
                                  .toString()),
                          SizedBox(height: 8),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  EsOutLineButton(
                                    '${state.todayData[index]['g_buy_size']}人团',
                                    textColor: EsColors.Primary,
                                    borderColor: EsColors.Primary,
                                    fontSize: EsSizes.XXXS,
                                    padding: EdgeInsets.symmetric(
                                        vertical: 1, horizontal: 4),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(right: 5),
                                    child: Text(
                                        '￥${state.todayData[index]['g_buy_price']}',
                                        style: TextStyle(
                                            color: EsColors.Primary,
                                            fontSize: EsSizes.SM,
                                            fontWeight: EsFontWeights.Normal)),
                                  ),
                                ],
                              ),
                              Text('已团${state.todayData[index]['buy_qty']}件',
                                  style: TextStyle(
                                      color: EsColors.ContentSecondary,
                                      fontSize: EsSizes.XS,
                                      fontWeight: EsFontWeights.Normal)),
                            ],
                          )
                        ],
                      ),
                    ),
                  );
                }))
      ]),
    );
  }

  /// 时间显示 ？？？
  Widget time() {
    return Row(children: [
      Container(
        padding: EdgeInsets.all(1),
        decoration: BoxDecoration(
            color: EsColors.Content, borderRadius: BorderRadius.circular(3)),
        child: Text('08',
            style: TextStyle(
                fontSize: EsSizes.XXS,
                color: EsColors.White,
                fontWeight: EsFontWeights.Medium)),
      ),
      SizedBox(width: 2),
      Text('：',
          style: TextStyle(
              fontSize: EsSizes.XXS,
              color: EsColors.Content,
              fontWeight: EsFontWeights.Medium)),
      Container(
        padding: EdgeInsets.all(1),
        decoration: BoxDecoration(
            color: EsColors.Content, borderRadius: BorderRadius.circular(3)),
        child: Text('39',
            style: TextStyle(
                fontSize: EsSizes.XXS,
                color: EsColors.White,
                fontWeight: EsFontWeights.Medium)),
      ),
      SizedBox(width: 2),
      Text('：',
          style: TextStyle(
              fontSize: EsSizes.XXS,
              color: EsColors.Content,
              fontWeight: EsFontWeights.Medium)),
      Container(
        padding: EdgeInsets.all(1),
        decoration: BoxDecoration(
            color: EsColors.Content, borderRadius: BorderRadius.circular(3)),
        child: Text('42',
            style: TextStyle(
                fontSize: EsSizes.XXS,
                color: EsColors.White,
                fontWeight: EsFontWeights.Medium)),
      )
    ]);
  }

  /// 热评榜
  Widget _hotCollage() {
    return Container(
      margin: EdgeInsets.all(10),
      decoration: EsDecoration.BoxShadowWithRadius,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(14, 10, 14, 4),
            child: Row(
              children: [
                Image.asset('assets/images/collage_fire.png'),
                SizedBox(width: 4),
                Text('热拼榜',
                    style: TextStyle(
                        fontSize: EsSizes.MD,
                        color: EsColors.Title,
                        fontWeight: EsFontWeights.Medium)),
                Expanded(child: SizedBox()),
                GestureDetector(
                    onTap: () {
                      Get.toNamed(RouteConfig.salesRankings,arguments:{'shop_id':state.collageShopId});
                    },
                    child: Row(children: [
                      Text('更多',
                          style: TextStyle(
                              fontSize: EsSizes.XS,
                              color: EsColors.ContentSecondary,
                              fontWeight: EsFontWeights.Normal)),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: EsSizes.XS,
                        color: EsColors.ContentSecondary,
                      )
                    ])),
              ],
            ),
          ),
          Container(
              height: MediaQuery.of(context).size.width / 3 + 40,
              width: double.infinity,
              child: ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemCount:
                      state.hotData.length >= 3 ? 3 : state.hotData.length,
                  itemBuilder: (context, index) {
                    return Stack(
                      children: [
                        GestureDetector(
                          child: Container(
                            padding: EdgeInsets.all(6),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                CachedImage(
                                    width:
                                        MediaQuery.of(context).size.width / 3 -
                                            20,
                                    height:
                                        MediaQuery.of(context).size.width / 3 -
                                            20,
                                    path: state.hotData[index]
                                            ['image_default_id']
                                        .toString()),
                                SizedBox(height: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        EsOutLineButton(
                                          '${state.hotData[index]['g_buy_size']}人团',
                                          textColor: EsColors.Primary,
                                          borderColor: EsColors.Primary,
                                          fontSize: EsSizes.XXXS,
                                          padding: EdgeInsets.symmetric(
                                              vertical: 1, horizontal: 4),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(right: 5),
                                          child: Text(
                                              '￥${state.hotData[index]['g_buy_price']}',
                                              style: TextStyle(
                                                  color: EsColors.Primary,
                                                  fontSize: EsSizes.SM,
                                                  fontWeight:
                                                      EsFontWeights.Normal)),
                                        ),
                                      ],
                                    ),
                                    Text(
                                        '已团${state.hotData[index]['buy_qty']}件',
                                        style: TextStyle(
                                            color: EsColors.ContentSecondary,
                                            fontSize: EsSizes.XS,
                                            fontWeight: EsFontWeights.Normal)),
                                  ],
                                )
                              ],
                            ),
                          ),
                          onTap: () {
                            print('aaaaaaaaa');
                            print(state.todayData);
                            print(index);
                            gopintuan(state.hotData[index]['g_buy_id'],state.collageShopId);
                          },
                        ),
                        Positioned(
                            left: 10,
                            top: 0,
                            child: Image.asset(
                                'assets/images/hot_top' +
                                    (index + 1).toString() +
                                    '.png',
                                width: 18,
                                height: 24,
                                fit: BoxFit.fill))
                      ],
                    );
                  }))
        ],
      ),
    );
  }

  /// 大家都在团
  Widget _tips() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(32, 10, 32, 14),
      child: Row(children: [
        Expanded(
            child: YpLine(height: 2, thickness: 2, color: EsColors.Primary)),
        SizedBox(width: 4),
        Text('大家都在团',
            style: TextStyle(
                fontSize: EsSizes.LG,
                color: EsColors.Primary,
                fontWeight: EsFontWeights.Medium)),
        SizedBox(width: 4),
        Expanded(
            child: YpLine(height: 2, thickness: 2, color: EsColors.Primary))
      ]),
    );
  }

  Widget _item(int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(10, 10, 10, 0),
      padding: EdgeInsets.all(10),
      decoration: EsDecoration.BoxShadowWithRadius,
      child: Row(
        children: [
          CachedImage(
              width: 130,
              height: 130,
              path: state.todayData[index]['image_default_id'].toString()),
          SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                    constraints: BoxConstraints(minHeight: 70),
                    child: Stack(children: [
                      Text(state.todayData[index]['item_title'].toString(),
                          maxLines: 3,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: EsColors.Title,
                              fontSize: EsSizes.SM,
                              fontWeight: EsFontWeights.Normal)),
                      Positioned(
                          top: 5,
                          child: Visibility(
                            visible: false,
                            child: Container(
                              padding: EdgeInsets.symmetric(horizontal: 3),
                              decoration: BoxDecoration(
                                  color: Color(0xfff50d2f),
                                  borderRadius: BorderRadius.circular(5)),
                              child: Text('新人团',
                                  style: TextStyle(
                                    color: EsColors.White,
                                    fontSize: EsSizes.XXXS,
                                    fontWeight: EsFontWeights.Normal,
                                  )),
                            ),
                          ))
                    ])),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 2, right: 5),
                              child: EsOutLineButton(
                                '${state.todayData[index]['g_buy_size']}人团',
                                textColor: EsColors.Primary,
                                borderColor: EsColors.Primary,
                                fontSize: EsSizes.XXXS,
                                padding: EdgeInsets.symmetric(
                                    vertical: 1, horizontal: 4),
                              ),
                            ),
                            Text('已团${state.todayData[index]['buy_qty']}件',
                                style: TextStyle(
                                    color: EsColors.ContentSecondary,
                                    fontSize: EsSizes.XS,
                                    fontWeight: EsFontWeights.Normal)),
                          ],
                        ),
                        Row(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 2, right: 1),
                              child: Text(
                                  '￥${state.todayData[index]['g_buy_price']}',
                                  style: TextStyle(
                                      color: EsColors.Primary,
                                      fontSize: EsSizes.XL,
                                      fontWeight: EsFontWeights.Normal)),
                            ),
                            Text('￥${state.todayData[index]['price']}',
                                style: TextStyle(
                                    decoration: TextDecoration.lineThrough,
                                    color: EsColors.ContentSecondary,
                                    fontSize: EsSizes.XS,
                                    fontWeight: EsFontWeights.Normal)),
                          ],
                        ),
                      ],
                    ),
                    Expanded(child: SizedBox()),
                    EsOutLineButton(
                      '去拼团',
                      bgColor: EsColors.Primary,
                      textColor: EsColors.White,
                      fontSize: EsSizes.MD,
                      fontWeight: EsFontWeights.Medium,
                      borderRadius: 16,
                      padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                      onTap: () {
                        gopintuan(state.todayData[index]['g_buy_id'],state.collageShopId);
                        print('去拼团');
                      },
                    )
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
